<?php
namespace globalunit\utils;

use QYS\Core\Config;

class EsHelper
{
    private $host;
    private $port;
    private $index;
    private $type;
    private $id;

    public function __construct($config)
    {
        $this->host = Config::get('eshost');
        $this->port = Config::get('esport');
        $this->index = isset($config['index']) ? $config['index'] : '';
        $this->type = isset($config['type']) ? $config['type'] : '_doc';
        $this->id = isset($config['id']) ? $config['id'] : '';
    }

    public function call($path, $method = 'GET', $content = null)
    {
        if(is_array($content)){
            $content = json_encode($content,JSON_UNESCAPED_UNICODE);
        }
        $res = CoroutineCurl::esCurl($this->host, $path, $this->port, false,  $method, $content);
        return $res;
    }

    public function isExist()
    {
        return $this->call('/'.$this->index, 'GET');
    }

    public function map($body = null)
    {
        return $this->call('/'.$this->index, 'PUT', $body);
    }

    public function add($body = null)
    {
        return $this->call('/'.$this->index.'/'.$this->type.'/'. $this->id.'/_create', 'PUT', $body);
    }

    public function save($where, $query = null)
    {
        return $this->call('/'.$this->index.'/'.$this->type.'/'.$where.'/_update', 'POST', $query);
    }

    public function count($query = null)
    {
        return $this->call('/'.$this->index.'/'.'_count?pretty', 'GET', $query);
    }

    public function search($query = null)
    {
        return $this->call('/'.$this->index.'/'.'_search?pretty' , 'GET', $query);
    }

    public function get($query = null)
    {
       return $this->call('/'.$this->index.'/'.$this->type.'/'.$query.'?pretty' , 'GET');
    }

    public function delete($query = null)
    {
        return $this->call('/'.$this->index.'/'.$this->type.'/'.$query , 'DELETE');
    }

    public function deleteAll($query = null)
    {
        return $this->call('/'.$this->index.'/'.$this->type.'/'.'_delete_by_query' , 'POST', $query);
    }

    public function drop()
    {
        return $this->call('/'.$this->index , 'DELETE');
    }
}